package com.erp.erp_project.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.erp.erp_project.service.BaseServcie;
import lombok.AllArgsConstructor;

import java.lang.reflect.Field;
import java.util.List;

/**
 * @author yh
 */
@AllArgsConstructor
public class BaseServiceImpl<T, E extends BaseMapper<T>> implements BaseServcie<T> {
    protected final E mapper;


    @Override
    public List<T> list(T bean) {
        QueryWrapper<T> queryWrapper = new QueryWrapper<T>();
        Class clazz = bean.getClass();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            try {
                String column;
                // 获取列名
                TableField tableField = field.getAnnotation(TableField.class);
                if (tableField == null) {
                    //  直接用名字作为这个列
                    column = field.getName();
                }else {
                    column = tableField.value();
                }
                // 获取值
                field.setAccessible(true);
                Object value = field.get(bean);
                if (value instanceof String && StrUtil.isBlank((CharSequence) value)) {
                    continue;
                }
                if (value != null) {
                    // 追加条件
                    queryWrapper.eq(column, value);
                }
            } catch (IllegalAccessException ignored) {

            }
        }

        return mapper.selectList(queryWrapper);
    }

    @Override
    public T selectById(Integer id) {
        return mapper.selectById(id);
    }

    @Override
    public int delectById(Integer id) {
        return mapper.deleteById(id);
    }

    @Override
    public int update(T bean) {
        return mapper.updateById(bean);
    }

    @Override
    public int insert(T bean) {
        return mapper.insert(bean);
    }


}
